const app = getApp();
var curpage = 1;
var page = 10;
var reset = true;
const util = require('../../utils/util.js')
Page({

    data: {
        stateType: '',
        order_group_list: [],
        curpage: 1,
        page: 10,
        reset: true,
        wechatpaySelected: true,
        showConfirmPay: true,
        rcb_pay: 0,
        pd_pay: 0,
        none_data: false
    },
    onLoad: function (options) {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
        util.share();
        var self = this;
        if (options.state_type) {
            this.setData({
                stateType: options.state_type,
            })
        }
        self.setData({
            hasmore: true
        })
        wx.getStorage({
            key: 'key',
            success: res => {
                self.setData({
                    key: res.data
                })
            }
        })
        if (app.globalData.openid) {
            this.setData({
                openid: app.globalData.openid
            })
        } else {
            wx.login({
                success: res => {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=connect&op=wechat_jscode',
                        data: {
                            js_code: res.code
                        },
                        method: 'GET',
                        dataType: 'json',
                        success: (res) => {
                            this.setData({
                                openid: res.data.datas.openid
                            })
                        },
                    });
                }
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.initPage();
    },
    initPage: function () {
        if (this.data.hasmore) {
            wx.showLoading()
            if (!this.data.reset) {
                this.setData({
                    order_group_list: [],
                    curpage: 1
                })
            }
            this.setData({
                reset: true
            })
            var self = this;
            wx.request({
                url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=commander_order_list',
                data: {
                    key: self.data.key,
                    state_type: self.data.stateType,
                    page: self.data.page,
                    curpage: self.data.curpage,
                },
                method: 'GET',
                dataType: 'json',
                success: res => {
                    self.setData({
                        curpage: self.data.curpage + 1
                    })
                    if (res.data.code == 200) {
                        var order_group_list = self.data.order_group_list.concat(res.data.datas.order_group_list);
                        if (order_group_list.length == 0) {
                            self.setData({
                                none_data: true
                            })
                        } else {
                            self.setData({
                                none_data: false
                            })
                        }
                        self.setData({
                            order_group_list: self.data.order_group_list.concat(res.data.datas.order_group_list),
                            hasmore: res.data.hasmore
                        })

                    } else {
                        self.setData({
                            none_data: true
                        })
                    }
                },
                fail: res => {
                    self.setData({
                        none_data: true
                    })
                },
                complete: () => {
                    wx.hideLoading()
                }
            })
        }

    },
    changeCurnav: function (e) {
        this.setData({
            stateType: e.target.dataset.state,
            hasmore: true,
            reset: false
        })
        this.initPage()
    },
    deleteOrder: function (e) {
        var order_id = e.target.dataset.order_id;
        var index = e.target.dataset.index;
        var self = this;
        wx.showModal({
            title: '是否移除订单？',
            content: '电脑端订单回收站可找回订单！',
            icon: 'success',
            success: res => {
                if (res.confirm) {
                    // 点击确认
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_order&op=order_delete',
                        data: {
                            key: self.data.key,
                            order_id: order_id
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: res => {
                            if (res.data.datas && res.data.datas == 1) {
                                self.data.order_group_list.splice(index, 1);
                                self.setData({
                                    order_group_list: self.data.order_group_list
                                })
                            } else {
                                wx.showToast({
                                    title: res.data.datas.error,
                                    icon: 'none'
                                })
                            }
                        }
                    })
                }
            }
        })
    },
    cancelOrder: function (e) {
        var order_id = e.target.dataset.order_id;
        var index = e.target.dataset.index;
        var child = e.target.dataset.child;
        var child_index = e.target.dataset.child_index;
        var self = this;
        wx.showModal({
            title: '',
            content: '确定取消订单？',
            icon: 'success',
            success: res => {
                if (res.confirm) {
                    // 点击确认
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_order&op=order_cancel',
                        data: {
                            key: self.data.key,
                            order_id: order_id
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: res => {
                            if (res.data.code == 200) {
                                if (child) {
                                    wx.redirectTo({
                                        url: '/pages/myOrder/myOrder?state_type=state_new'
                                    })
                                } else {
                                    self.data.order_group_list.splice(index, 1);
                                }

                                self.setData({
                                    order_group_list: self.data.order_group_list
                                })
                            } else {
                                wx.showToast({
                                    title: res.data.datas.error,
                                    icon: 'none'
                                })
                            }
                        }
                    })
                }
            }
        })
    },
    reBuy: function (e) {
        var goods_ids = e.target.dataset.goods_ids;
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=wechat_rebuy',
            data: {
                key: self.data.key,
                goods_ids: goods_ids
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code == 200) {
                    var cart = goods_ids.split('|');
                    var quantity = cart.length;
                    wx.getStorage({
                        key: 'cart_count',
                        success: (res) => {
                            wx.setTabBarBadge({
                                index: 3,
                                text: String(res.data + quantity)
                            })
                            wx.setStorage({
                                key: 'cart_count',
                                data: res.data + quantity
                            })
                        }
                    })

                    wx.switchTab({
                        url: '../cart/cart'
                    })
                } else {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none'
                    })
                }
            }
        })
    },
    confirmReceive: function (e) {
        var order_id = e.target.dataset.order_id;
        var index = e.target.dataset.index;
        var self = this;
        wx.showModal({
            title: '',
            content: '确定收到了货物吗？',
            icon: 'success',
            success: res => {
                if (res.confirm) {
                    // 点击确认
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_order&op=order_receive',
                        data: {
                            key: self.data.key,
                            order_id: order_id
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: res => {
                            if (res.data.code == 200) {
                                self.data.order_group_list.splice(index, 1);
                                self.setData({
                                    order_group_list: self.data.order_group_list
                                })
                            } else {
                                wx.showToast({
                                    title: res.data.datas.error,
                                    icon: 'none'
                                })
                            }
                        }
                    })
                }
            }
        })
    },
    util1: function (currentStatu) {
        var self = this;
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear',
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(400).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatus1: false,
                    rcbState: false,
                    pdState: false,
                    showRercb: false,
                    showRepd: false,
                    rcb_pay: 0,
                    pd_pay: 0,
                    wechatpaySelected: true
                });
            }
        }.bind(this), 200)
        if (currentStatu == "open") {
            this.setData({
                showModalStatus1: true
            });
        }
    },
    goto_pay: function (e) {
        var currentStatu = e.currentTarget.dataset.statu;
        this.util1(currentStatu)

        var pay_sn = e.target.dataset.pay_sn;
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=pay',
            data: {
                key: self.data.key,
                pay_sn: pay_sn
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code != 200) {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none'
                    })
                } else {
                    self.setData({
                        pay_info: res.data.datas.pay_info,
                        wechat_paynum: '￥' + res.data.datas.pay_info.pay_amount
                    })
                }
            }
        })

    },
    orderUp: function (e) {
        var currentStatu = e.currentTarget.dataset.statu;
        this.util1(currentStatu)
    },
    orderClose: function () {
        this.util1("close")
    },
    payPsw: function (e) {
        if (this.data.rcb_pay == 1 || this.data.pd_pay == 1) {
            this.setData({
                payPsw: e.detail.value
            })
        } else {
            this.setData({
                payPsw: ''
            })
        }
    },
    confirmPay: function (e) {
        if (!this.data.showConfirmPay) {
            return;
        }
        this.setData({
            showConfirmPay: false
        })
        var self = this;
        var pay_sn = e.target.dataset.pay_sn;
        var password;
        if (this.data.pd_pay == 1 || this.data.rcb_pay == 1) {
            password = self.data.payPsw;
        } else {
            password = '';
        }
        wx.request({

            url: app.globalData.ApiUrl + '/index.php?act=member_payment&op=wechat_pay',
            data: {
                key: self.data.key,
                pay_sn: pay_sn,
                rcb_pay: self.data.rcb_pay,
                pd_pay: self.data.pd_pay,
                password: password,
                payment_code: 'wxpay'
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: (res) => {
                if (res.data.code != 200) {
                    self.setData({
                        showConfirmPay: true
                    })
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none'
                    })
                } else {
                    if (res.data.datas.pay_code == 'available') {
                        self.setData({
                            showConfirmPay: true
                        })
                        wx.redirectTo({
                            url: '../myOrder/myOrder?state_type=state_send'
                        })
                    } else {
                        let api_pay_amount;
                        let account = self.data.pay_info
                        if (self.data.rcb_pay == 1 && self.data.pd_pay == 0) {
                            api_pay_amount = account.pay_amount - account.member_available_rcb
                        }
                        if (self.data.rcb_pay == 0 && self.data.pd_pay == 1) {
                            api_pay_amount = account.pay_amount - account.member_available_pd
                        }
                        if (self.data.rcb_pay == 1 && self.data.pd_pay == 1) {
                            api_pay_amount = account.pay_amount - account.member_available_rcb - account.member_available_pd
                        }
                        if (self.data.rcb_pay == 0 && self.data.pd_pay == 0) {
                            api_pay_amount = account.pay_amount
                        }

                        wx.request({
                            url: app.globalData.ApiUrl + '/index.php?act=member_payment&op=pay_new_mini',
                            method: 'GET',
                            data: {
                                key: self.data.key,
                                open_id: self.data.openid,
                                pay_sn: pay_sn,
                                api_pay_amount: api_pay_amount
                            },
                            success: payres => {
                                if (payres.data.code == 'error') {
                                    wx.showToast({
                                        title: payres.data.msg,
                                        icon: 'none'
                                    })
                                    self.setData({
                                        showConfirmPay: true
                                    })
                                    return;
                                }
                                wx.requestPayment({
                                    timeStamp: payres.data.timeStamp,
                                    nonceStr: payres.data.nonceStr,
                                    package: payres.data.package,
                                    signType: 'MD5',
                                    paySign: payres.data.paySign,
                                    success(resa) {
                                        self.setData({
                                            showConfirmPay: true
                                        })
                                        wx.redirectTo({
                                            url: '../myOrder/myOrder?state_type=state_send'
                                        })
                                    },
                                    fail(res) {
                                        if (res.errMsg == "requestPayment:fail cancel") {
                                            self.setData({
                                                showConfirmPay: true
                                            })
                                            wx.redirectTo({
                                                url: '../myOrder/myOrder?state_type=state_new'
                                            })
                                        }
                                    }
                                })
                            }
                        })
                    }
                }
            }
        });
    },
    checkLogistics: function (e) {
        var order_id = e.target.dataset.order_id;
        wx.navigateTo({
            url: '../order_delivery/order_delivery?order_id=' + order_id,
        })
    },
    evaluateOrder: function (e) {
        var order_id = e.target.dataset.order_id;
        wx.navigateTo({
            url: '../member_evaluation/member_evaluation?order_id=' + order_id,
        })
    },
    evaluateOrderAgain: function (e) {
        var order_id = e.target.dataset.order_id;
        wx.navigateTo({
            url: '../member_evaluation_again/member_evaluation_again?order_id=' + order_id,
        })
    },
    checkGetMap: function (e) {
        let chain_info = e.currentTarget.dataset.chain_info;
        let latitude = chain_info.lat * 1;
        let longitude = chain_info.lng * 1;
        let chain_address = chain_info.chain_address;
        wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: chain_address
        })
    },
    onReachBottom: function () {
        this.initPage()
    },
    onPageScroll: function (e) {
        this.setData({
            scrollTop: e.scrollTop
        })
    },
    goTop: function (e) { // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    onShareAppMessage: function () {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        }
    }
})